<?php

// +----------------------------------------------------------------------
// | 版权所有 2017-2027 云南环拓科技有限公司，并保留所有权利。
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2027 http://www.yn123.com All rights reserved.
// +----------------------------------------------------------------------
// | Notice: This code is not open source, it is strictly prohibited
// |         to distribute the copy, otherwise it will pursue its
// |         legal responsibility.
// | 注意：  这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用,
// |        不允许对程序代码以任何形式任何目的的再发布。
// +----------------------------------------------------------------------
// | Author: feraner <feraner@163.com> 
// | Date: 2020/1/3
// +----------------------------------------------------------------------

namespace app\common\services\statistics;

use app\common\facade\Arr;
use library\tools\Data;
use think\Db;

/**
 * 二手市场分析
 * Class MarketHandleService
 * @package app\common\services\statistics
 * @author feraner<feraner@163.com>
 * @date 2020/1/3
 */
class MarketHandleService extends BasicHandleService
{

    /**
     * 二手市场 api
     * @var string
     */
    private $apiMarketSuffix = 'market';

    /**
     * 二手市场 web
     * @var string
     */
    private $webMarketSuffix = 'market';



    public function __construct()
    {
        parent::__construct();
    }


    /**
     * @param $handleData
     *
     * @return mixed|void
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function handle($handleData)
    {
        if ($this->isHandle($handleData)) {

            //是否需要增加UV
            $this->addUv = $this->addUvNum(
                Arr::get($handleData, 'userId'),
                Arr::get($handleData, 'logId')
            );

            //二手市场模块
            $this->__handleMarketModule($handleData);

            //二手市场类型
            $this->__handleMarketType($handleData);



        }
    }




    /**
     * 处理二手市场类型点击量统计
     * @param $handleData
     *
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    private function __handleMarketType($handleData)
    {
        $paramsArr = Arr::get($handleData, 'params', []);
        if ($marketType = Arr::get($paramsArr, 'marketType')) {
            $updateData = [
                'type'          => 1,
                'market_type'      => $marketType,
                'click'         => Db::raw('click + 1'),
                'start_time'    => $this->todayStart,
                'end_time'      => $this->todayEnd,
            ];
            if ($this->addUv) {
                $updateData['uv'] = Db::raw('uv + 1');
            }
            if ($dayStatId = $this->__checkMarketTypeStatExit($updateData)) {
                $updateData['id'] = $dayStatId;
            }
            Data::save('behavior_market_type_stat', $updateData);
        }
    }


    /**
     * 检测二手市场类型统计是否已经存在
     * @param $data
     *
     * @return int
     */
    private function __checkMarketTypeStatExit($data)
    {
        return Db::name('behavior_market_type_stat')
            ->where('type', Arr::get($data, 'type'))
            ->where('market_type', Arr::get($data, 'market_type'))
            ->where('start_time', Arr::get($data, 'start_time'))
            ->value('id') ?: 0;
    }









    /**
     * 处理二手市场模块点击统计
     * @param $handleData
     *
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    private function __handleMarketModule($handleData)
    {
        if ($this->isWeb) {

            $dayData = [
                'type'          => 1,
                'market_click'     => Db::raw('market_click + 1'),
                'start_time'    => $this->todayStart,
                'end_time'      => $this->todayEnd,
            ];
            if ($this->addUv) {
                $dayData['market_uv'] = Db::raw('market_uv + 1');
            }

            if ($statId = $this->checkModuleStatExit($dayData)) {
                $dayData['id'] = $statId;
            }

            Data::save('behavior_module_stat', $dayData);

        }
    }



    /**
     * 判断是否是该模块
     * @param $handleData
     *
     * @return bool|mixed
     */
    protected function isHandle($handleData)
    {
        $this->isWeb = false;
        $this->isApi = false;

        //api 接口
        if (Arr::valueEq($handleData['urlArr'], 0, $this->apiSuffix) &&
            Arr::valueEq($handleData['urlArr'], 1, $this->apiMarketSuffix)) {
            $this->isApi = true;
            return true;
        }

        //web界面
        if (Arr::valueEq($handleData['urlArr'], 0, $this->webSuffix) &&
            Arr::valueEq($handleData['urlArr'], 1, $this->webMarketSuffix)) {
            $this->isWeb = true;
            return true;
        }

        return false;
    }


    /**
     * 处理二手商品 月度 + 总量
     * @return mixed|void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function handleMonthAndTotal()
    {
        //marketTyep 月度 + 总量统计
        $marketTypeList = Db::name('market_type')
            ->where('status', 1)
            ->field('id, status')
            ->select() ?: [];
        if ($marketTypeList) {
            foreach ($marketTypeList as $item) {
                $this->__handleMarketTypeMonthAndTotal($item);
            }
        }
    }



    /**
     * 处理一个二手商品类型 月度 + 总量
     * @param $jobType
     *
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    private function __handleMarketTypeMonthAndTotal($marketType)
    {
        //月度数据
        $monthResult = Db::name('behavior_market_type_stat')
            ->where('type', 1)
            ->where('market_type', Arr::get($marketType, 'id'))
            ->where('start_time', '>=', $this->monthStart)
            ->where('end_time', '<=', $this->monthEnd)
            ->field('SUM(click) as click')
            ->field('SUM(uv) as uv')
            ->find() ?: [];

        $monthData = [
            'type'          => 2,
            'market_type'   => Arr::get($marketType, 'id'),
            'click'         => Arr::get($monthResult, 'click', 1),
            'uv'            => Arr::get($monthResult, 'uv', 1),
            'start_time'    => $this->monthStart,
            'end_time'      => $this->monthEnd
        ];
        if ($monthStatId = $this->__checkMarketTypeStatExit($monthData)) {
            $monthData['id'] = $monthStatId;
        }
        Data::save('behavior_market_type_stat', $monthData);

        //总量数据
        $totalResult = Db::name('behavior_market_type_stat')
            ->where('type', 2)
            ->where('market_type', Arr::get($marketType, 'id'))
            ->field('SUM(click) as click')
            ->field('SUM(uv) as uv')
            ->find() ?: [];

        $totalData = [
            'type'          => 3,
            'market_type'      => Arr::get($marketType, 'id'),
            'click'         => Arr::get($totalResult, 'click', 1),
            'uv'            => Arr::get($totalResult, 'uv', 1),
            'start_time'    => 0,
            'end_time'      =>0
        ];
        if ($totalStatId = $this->__checkMarketTypeStatExit($totalData)) {
            $totalData['id'] = $totalStatId;
        }
        Data::save('behavior_market_type_stat', $totalData);
    }








}
